var isInitFaculty = false;
var isInitFacultyProject = false;
var source = {
			localdata: [],
			datatype: "array"
		};
var dataAdapter = new $.jqx.dataAdapter(source, {
	loadComplete: function (data) { },
	loadError: function (xhr, status, error) { }    
});
$(document).ready(function() {
	initEvent();
	$('#loginDialog').modal({
		backdrop: 'static',
		show: false
	});
	$('#successDialog').modal({
		show: false
	});
	
	$('#failDialog').modal({
		show: false
	});
	//initView();
	checkLogin();
});

function initEvent(){

	$('#loginButton').click(function(){
		login();
	});
	
	$('#insertNews').click(function(){
		insertNews();
	});
	
	$('#updateNews').click(function(){
		updateNews();
	});
	
	$('#editNews').click(function(){
		editNews();
	});
	
	$('#deleteNews').click(function(){
		deleteNews();
	});
	
	$('#clearNews').click(function(){
		resetNewsFrom();
	});
	
	$('#insertFaculty').click(function(){
		insertFaculty();
	});
	
	$('#updateFaculty').click(function(){
		updateFaculty();
	});
	
	$('#editFaculty').click(function(){
		editFaculty();
	});
	
	$('#deleteFaculty').click(function(){
		deleteFaculty();
	});
	
	$('#clearFaculty').click(function(){
		resetFacultyFrom();
	});
	
	$('#faculty_project_refresh_faculty').click(function(){
		refreshFaculty();
	});
	
	$('#faculty_project_refresh_project').click(function(){
		refreshProject();
	});
	
	$('#update_faculty_project').click(function(){
		updateFacultyProject();
	});
	
	$('#faculty_project_get_project').click(function(){
		getProject();
	});
	
	$('#logout').click(function(){
		logout();
	});
}

function initView(){
	
	$('#news_date').datetimepicker();
	
	$("#gridNews").jqxGrid({
		theme: "bootstrap", 
		width: "100%",
		sortable: true,
		pageable: true,
		source: dataAdapter,
		columns: [
			{ text: 'Id', datafield: 'Id', width: '10%' },
			{ text: 'Tiêu đề', datafield: 'Title', width: '18%' },
			{ text: 'Ngày', datafield: 'Date', width: '18%' },
			{ text: 'Hình ảnh', datafield: 'Image', width: '18%', cellsalign: 'right' },
			{ text: 'Tóm lượt', datafield: 'Summary', width: '18%', cellsalign: 'right', cellsformat: 'c2' },
			{ text: 'Chi tiết', datafield: 'Desc', width: '18%', cellsalign: 'right', cellsformat: 'c2' }
		],
	});
	$('#gridNews').on('rowclick', function (event) {
		var datarow = $("#gridNews").jqxGrid('getrowdata', event.args.rowindex);
		$('#news_id').val(datarow.Id);
		$('#news_title').val(datarow.Title);
		$('#news_summary').val(datarow.Summary);
		$('#news_date').val(datarow.Date);
		CKEDITOR.instances.news_desc.setData(datarow.Desc);
		$('#review_image').attr('src', datarow.Image);
	});
	
	CKEDITOR.replace('news_desc');
}

function initFaculty(){
	if(!isInitFaculty){
		$("#gridFaculty").jqxGrid({
			theme: "bootstrap", 
			width: "100%",
			sortable: true,
			pageable: true,
			source: dataAdapter,
			columns: [
				{ text: 'Id', datafield: 'Id', width: '5%' },
				{ text: 'Họ tên', datafield: 'Name', width: '15%' },
				{ text: 'Học vị', datafield: 'Diploma', width: '15%' },
				{ text: 'Bộ môn', datafield: 'Department', width: '15%', cellsalign: 'right' },
				{ text: 'Hình ảnh', datafield: 'Image', width: '5%', cellsalign: 'right', cellsformat: 'c2' },
				{ text: 'Giới thiệu', datafield: 'Desc', width: '15%', cellsalign: 'right', cellsformat: 'c2' },
				{ text: 'Quá trình công tác', datafield: 'Process', width: '15%', cellsalign: 'right', cellsformat: 'c2' },
				{ text: 'Thành tích khác', datafield: 'Performance', width: '15%', cellsalign: 'right', cellsformat: 'c2' }
			],
		});
		$('#gridFaculty').on('rowclick', function (event) {
			var datarow = $("#gridFaculty").jqxGrid('getrowdata', event.args.rowindex);
			$('#faculty_id').val(datarow.Id);
			$('#faculty_name').val(datarow.Name);
			$('#faculty_diploma').val(datarow.Diploma);
			$('#faculty_department').val(datarow.Department);
			/*$('#faculty_desc').val(datarow.Desc);
			$('#faculty_process').val(datarow.Process);
			$('#faculty_performance').val(datarow.Performance);*/
			CKEDITOR.instances.faculty_desc.setData(datarow.Desc);
			CKEDITOR.instances.faculty_process.setData(datarow.Process);
			CKEDITOR.instances.faculty_performance.setData(datarow.Performance);
			$('#faculty_review').attr('src', datarow.Image);
		});
		isInitFaculty = true;
	}
}

function initFacultyProject(){
	if(!isInitFacultyProject){
		$("#faculty_project_faculty_grid").jqxGrid({
			theme: "bootstrap", 
			width: "100%",
			height: '200px',
			sortable: true,
			pageable: true,
			source: dataAdapter,
			columns: [
				{ text: 'Id', datafield: 'Id', width: '10%' },
				{ text: 'Họ tên', datafield: 'Name', width: '30%' },
				{ text: 'Học vị', datafield: 'Diploma', width: '30%' },
				{ text: 'Bộ môn', datafield: 'Department', width: '30%', cellsalign: 'right' }
			]
		});
		
		$('#faculty_project_faculty_grid').on('rowclick', function (event) {
			var datarow = $("#faculty_project_faculty_grid").jqxGrid('getrowdata', event.args.rowindex);
			$('#faculty_project_id').val(datarow.Id);
		});
		
		$("#faculty_project_grid").jqxGrid({
			theme: "bootstrap", 
			width: "100%",
			sortable: true,
			source: dataAdapter,
			columns: [
				{ text: 'Id', datafield: 'Id', width: '10%' },
				{ text: 'Tiêu đề', datafield: 'Title', width: '70%' },
				{ text: 'Delete', datafield: 'Delete', columntype: 'button', cellsrenderer: function () {
					return "Delete";
					}, buttonclick: function (row) {
						var selectedrowindex = $("#faculty_project_grid").jqxGrid('getselectedrowindex');
						var rowscount = $("#faculty_project_grid").jqxGrid('getdatainformation').rowscount;
						if (selectedrowindex >= 0 && selectedrowindex < rowscount) {
							var id = $("#faculty_project_grid").jqxGrid('getrowid', selectedrowindex);
							var commit = $("#faculty_project_grid").jqxGrid('deleterow', id);
						}
					}
				},
			]
		});
		
		$("#faculty_project_project_grid").jqxGrid({
			theme: "bootstrap", 
			width: "100%",
			sortable: true,
			pageable: true,
			source: dataAdapter,
			columns: [
				{ text: 'Id', datafield: 'Id', width: '10%' },
				{ text: 'Tiêu đề', datafield: 'Title', width: '18%' },
				{ text: 'Ngày', datafield: 'Date', width: '18%' },
				{ text: 'Hình ảnh', datafield: 'Image', width: '18%', cellsalign: 'right' },
				{ text: 'Tóm lượt', datafield: 'Summary', width: '18%', cellsalign: 'right', cellsformat: 'c2' },
				{ text: 'Chi tiết', datafield: 'Desc', width: '18%', cellsalign: 'right', cellsformat: 'c2' }
			]
		});
		
		$('#faculty_project_project_grid').on('rowclick', function (event) {
			var datarow = $("#faculty_project_project_grid").jqxGrid('getrowdata', event.args.rowindex);
			$("#faculty_project_grid").jqxGrid("addrow", null, datarow, "last");
		});
		isInitFacultyProject = true;
	}
}

function login(){
	$('#loading').show();
	var params = {
		action: 'login',
		username: $('#username').val(),
		password: $('#password').val()
	};
	$.ajax({
		url: URL_AUTHORIZED,
		type: 'POST',
		data: params,
		success: function(res){
			$('#loading').hide();
			var user = JSON.parse(res);
			if(user.username){
				$('#loginDialog').hide();
			}
			initView();
		},
		error: function(err){
			$('#loading').hide();
		}
	});
}

function checkLogin(){
	$('#loading').show();
	var params = {
		action: 'checkLogin',
	};
	$.ajax({
		url: URL_AUTHORIZED,
		type: 'POST',
		data: params,
		async: false,
		success: function(res){
			$('#loading').hide();
			var user = JSON.parse(res);
			if(user.username){
				initView();
			} else {
				$('#loginDialog').modal('show');
			}
			
		},
		error: function(err){
			$('#loading').hide();
			$('#loginDialog').modal('show');
		}
	});
}

function logout(){
	$('#loading').show();
	var params = {
		action: 'logout',
	};
	$.ajax({
		url: URL_AUTHORIZED,
		type: 'POST',
		data: params,
		async: false,
		success: function(res){
			$('#loading').hide();
			location.reload();
		},
		error: function(err){
			$('#loading').hide();
			location.reload();
		}
	});
}

function insertNews(){
	$('#loading').show();
	var data = getNewsForm('insert');
	var url = detectURL();
	resetNewsFrom();
	sendRequestWithFile(url, 'POST', data, function(res){
		if(res == 'true'){
			successDialog();
		} else {
			failDialog();
		}
	}, function(err){failDialog();});
}

function updateNews(){
	var params = {
		action: 'getAll'
	};
	$('#loading').show();
	sendRequest(detectURL(), 'GET', params, function(res){
		if(res){
			var data = JSON.parse(res);
			var tempSource = {
				localdata: data,
				datatype: "array"
			};
			$("#gridNews").jqxGrid({ source: tempSource });
		}
		$('#loading').hide();
	}, function(err){
		failDialog();
	});
}

function editNews(){
	$('#loading').show();
	var data = getNewsForm('update');
	var url = detectURL();
	resetNewsFrom();
	sendRequestWithFile(url, 'POST', data, function(res){
		if(res == 'true'){
			successDialog();
		} else {
			failDialog();
		}
	}, function(err){failDialog();});
}

function deleteNews(){
	var params = {
		action: 'delete',
		id: $('#news_id').val()
	};
	$('#loading').show();
	resetNewsFrom();
	sendRequest(detectURL(), 'POST', params, function(res){
		console.log(res);
		if(res == 'true'){
			successDialog();
		} else {
			failDialog();
		}
	}, function(err){
		failDialog();
	});
}

function detectURL(){
	var tempReturn = '';
	switch($("input[name=optradio]:checked" ).val()){
		case 'radioInformation': tempReturn = URL_INFORMATION; break;
		case 'radioNews': tempReturn = URL_NEWS; break;
		case 'radioActivity': tempReturn = URL_ACTIVITY; break;
		case 'radioProject': tempReturn = URL_PROJECT; break;
		case 'radioEvents': tempReturn = URL_EVENTS; break;
		default : break;
	}
	return tempReturn;
}

function successDialog(){
	$('#loading').hide();
	if($("#autorefresh").is(':checked')){
		switch($('.tab-pane.active').attr('id')){
			case 'news': $('#updateNews').click(); break;
			case 'faculty': $('#updateFaculty').click(); break;faculty_project_refresh_faculty
			case 'faculty_project': $('#faculty_project_refresh_project').click(); 
									$('#faculty_project_refresh_faculty').click();
									break;
			default: break;
		}
	}
	$('#successDialog').modal('show');
}

function failDialog(){
	$('#loading').hide();
	$('#failDialog').modal('show');
}

function resetNewsFrom(){
	$('#news_id').val('');
	$('#news_title').val('');
	$('#news_summary').val('');
	$('#news_date').val('');
	//$('#news_desc').val('');
	CKEDITOR.instances.news_desc.setData('');
	if($('#new_image').defaultValue){
		$('#news_image').src($('#new_image').defaultValue);
	}
	//$('#review_image').attr('src', '');
	$('#news_image_div').html('');
	$('#news_image_div').html('<label for="message-text" class="control-label">Hình ảnh:</label><div class="fileinput fileinput-new" data-provides="fileinput"><div class="fileinput-new thumbnail" style="width: 200px; height: 150px;"><img id="review_image" data-src="holder.js/100%x100%"></div><div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;"></div><div><span class="btn btn-default btn-file"><span class="fileinput-new">Select image</span><span class="fileinput-exists">Change</span><input id="news_image" type="file" ></span><a href="#" class="btn btn-default fileinput-exists" data-dismiss="fileinput">Remove</a></div></div>');
}

function getNewsForm(action){
	var data = new FormData();
	if($('#news_image')[0].files[0]){
		data.append('image', $('#news_image')[0].files[0]);
	}
	data.append('action', action);
	data.append('id', $('#news_id').val());
	data.append('title', $('#news_title').val());
	data.append('summary', $('#news_summary').val());
	data.append('date', $('#news_date').val());
	//data.append('desc', $('#news_desc').val());
	data.append('desc', CKEDITOR.instances.news_desc.getData());
	return data;
}

function insertFaculty(){
	$('#loading').show();
	var data = getFacultyForm('insert');
	resetFacultyFrom();
	sendRequestWithFile(URL_FACULTY, 'POST', data, function(res){
		if(res == 'true'){
			successDialog();
		} else {
			failDialog();
		}
	}, function(err){failDialog();});
}

function updateFaculty(){
	var params = {
		action: 'getAll'
	};
	$('#loading').show();
	sendRequest(URL_FACULTY, 'GET', params, function(res){
		var data = JSON.parse(res);
		var tempSource = {
			localdata: data,
			datatype: "array"
		};
		$("#gridFaculty").jqxGrid({ source: tempSource });
		$('#loading').hide();
	}, function(err){
		failDialog();
	});
}

function editFaculty(){
	$('#loading').show();
	var data = getFacultyForm('update');
	resetFacultyFrom();
	sendRequestWithFile(URL_FACULTY, 'POST', data, function(res){
		console.log(res);
		if(res == 'true'){
			successDialog();
		} else {
			failDialog();
		}
	}, function(err){failDialog();});
}

function deleteFaculty(){
	var params = {
		action: 'delete',
		id: $('#faculty_id').val()
	};
	$('#loading').show();
	resetFacultyFrom();
	sendRequest(URL_FACULTY, 'POST', params, function(res){
		if(res == 'true'){
			successDialog();
		} else {
			failDialog();
		}
	}, function(err){
		failDialog();
	});
}

function resetFacultyFrom(){
	$('#faculty_id').val('');
	$('#faculty_name').val('');
	$('#faculty_diploma').val('');
	$('#faculty_department').val('');
	/*$('#faculty_desc').val('');
	$('#faculty_process').val('');
	$('#faculty_performance').val('');*/
	CKEDITOR.instances.faculty_desc.setData('');
	CKEDITOR.instances.faculty_process.setData('');
	CKEDITOR.instances.faculty_process.setData('');
	if($('#faculty_image').defaultValue){
		$('#faculty_image').src($('#faculty_image').defaultValue);
	}
	$('#faculty_review').attr('src', '');
}

function getFacultyForm(action){
	var data = new FormData();
	if($('#faculty_image')[0].files[0]){
		data.append('image', $('#faculty_image')[0].files[0]);
	}
	data.append('action', action);
	data.append('id', $('#faculty_id').val());
	data.append('name', $('#faculty_name').val());
	data.append('diploma', $('#faculty_diploma').val());
	data.append('department', $('#faculty_department').val());
	/*data.append('desc', $('#faculty_desc').val());
	data.append('process', $('#faculty_process').val());
	data.append('performance', $('#faculty_performance').val());*/
	data.append('desc', CKEDITOR.instances.faculty_desc.getData());
	data.append('process', CKEDITOR.instances.faculty_process.getData());
	data.append('performance', CKEDITOR.instances.faculty_performance.getData());
	return data;
}

function refreshFaculty(){
	var params = {
		action: 'getAll'
	};
	$('#loading').show();
	sendRequest(URL_FACULTY, 'GET', params, function(res){
		var data = JSON.parse(res);
		var source = {
			localdata: data,
			datatype: "array"
		};
		$("#faculty_project_faculty_grid").jqxGrid({ source: source });
		$('#loading').hide();
	}, function(err){
		failDialog();
	});
}

function refreshProject(){
	var params = {
		action: 'getAll'
	};
	$('#loading').show();
	sendRequest(URL_FACULTY, 'GET', params, function(res){
		var data = JSON.parse(res);
		var source = {
			localdata: data,
			datatype: "array"
		};
		$("#faculty_project_faculty_grid").jqxGrid({ source: source });
		$('#loading').hide();
	}, function(err){
		failDialog();
	});
}

function refreshProject(){
	var params = {
		action: 'getAll'
	};
	$('#loading').show();
	sendRequest(URL_PROJECT, 'GET', params, function(res){
		var data = JSON.parse(res);
		var source = {
			localdata: data,
			datatype: "array"
		};
		$("#faculty_project_project_grid").jqxGrid({ source: source });
		$('#loading').hide();
	}, function(err){
		failDialog();
	});
}

function getProject(){
	var params = {
		action: 'getById',
		idFaculty: $('#faculty_project_id').val()
	};
	$('#loading').show();
	sendRequest(URL_FACULTY_PROJECT, 'GET', params, function(res){
		console.log(res);
		var data = JSON.parse(res);
		var source = {
			localdata: data,
			datatype: "array"
		};
		$("#faculty_project_grid").jqxGrid({ source: source });
		$('#loading').hide();
	}, function(err){
		failDialog();
	});
}

function updateFacultyProject(){
	var griddata = $('#faculty_project_grid').jqxGrid('getdatainformation');
	var rows = [];
	for (var i = 0; i < griddata.rowscount; i++){
		rows.push($('#faculty_project_grid').jqxGrid('getrenderedrowdata', i).Id);
	}
	console.log(JSON.stringify(rows));
	var params = {
		action: 'insert',
		projectList: JSON.stringify(rows),
		idFaculty: $('#faculty_project_id').val()
	};
	$('#loading').show();
	$('#faculty_project_grid').jqxGrid('clear');
	sendRequest(URL_FACULTY_PROJECT, 'POST', params, function(res){
		console.log(res);
		successDialog();
	}, function(err){
		failDialog();
	});
}